<?php
namespace Aincrid\MySwoole;

use Aincrid\MySwoole\Facade\Container;

class App
{
    private static ?App $instance = null;

    private static ?\Aincrid\MySwoole\Container $container = null;

    protected bool $isRun = false;

    private function __construct()
    {
    }

    private function __clone(): void
    {
    }

    public static function makeInstance(): App
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function run()
    {
        try {
            if ($this->isRun) {
                throw new \Exception('APP is running');
            }
            \Swoole\Runtime::enableCoroutine(SWOOLE_HOOK_ALL);

            // 获取容器类
            $container = static::getContainer();

            // 绑定App实例到容器
            Container::bind(__CLASS__, self::$instance);

            // 初始化基础类到容器
            $container->initInstances();

            // 初始化路由
            $this->initRouter();

            $this->isRun = true;

            $router = Container::get(\Aincrid\MySwoole\Router\Router::class);
            // 初始化服务器
            $server = Container::get(Server::class);

            $server->start();
        } catch (\Exception $e) {
            var_dump($e);
        } finally {

        }
    }


    protected function initRouter()
    {
        require_once(ROOT_DIR . '/routes/route.php');
    }


    public function getContainer(): \Aincrid\MySwoole\Container
    {
        if (is_null(self::$container)) {
            self::$container = new \Aincrid\MySwoole\Container();
            self::$container->bind(\Aincrid\MySwoole\Container::class, self::$container);
        }
        return self::$container;
    }

}